package com.yx.fx.log.web.api;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yx.fx.common.model.ExcelAlias;
import com.yx.fx.common.model.response.Outcome;
import com.yx.fx.common.utils.ExcelUtil;
import com.yx.fx.log.db.entity.Logger;
import com.yx.fx.log.web.business.LoggerBusiness;
import com.yx.fx.log.web.model.find.FindLoggerPage;
import com.yx.fx.log.web.model.save.SaveLogger;
import com.yx.fx.log.web.model.update.UpdateLogger;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Size;
import java.util.List;

/**
 * @author 杨智杰
 * @date 2021/8/11 13:20
 */
@Api(tags = "日志相关接口")
@RestController
@RequestMapping("/log/logger")
public class LoggerApi {

    @Resource
    private LoggerBusiness loggerBusiness;

    @PostMapping
    @ApiOperation("新增日志")
    public Outcome save(@RequestBody @Valid SaveLogger param) {
        return Outcome.status(loggerBusiness.save(param));
    }

    @PutMapping
    @ApiOperation("修改日志")
    public Outcome update(@RequestBody @Valid UpdateLogger param) {
        return Outcome.status(loggerBusiness.update(param));
    }

    @GetMapping
    @ApiOperation("日志分页")
    public Outcome<IPage<Logger>> page(FindLoggerPage param) {
        return Outcome.success(loggerBusiness.page(param));
    }

    @DeleteMapping
    @ApiOperation("删除日志")
    public Outcome delete(@RequestParam @Valid @Size(min = 1) List<Long> id) {
        return Outcome.status(loggerBusiness.delete(id));
    }

    @PostMapping("/setCaChe")
    public void setCaChe(@RequestBody @Valid SaveLogger param) {
        loggerBusiness.setCaChe(param);
    }

    @GetMapping("/downExcl")
    @ApiOperation(value = "下载excl表格", produces = "application/octet-stream")
    public void downExcl(FindLoggerPage param) {
        IPage<Logger> page = loggerBusiness.page(param);
        ExcelUtil.downExcel(page.getRecords(), CollUtil.newArrayList(
                ExcelAlias.makeAlias("id", "主键"),
                ExcelAlias.makeAlias("method", "请求类型"),
                ExcelAlias.makeAlias("scheme", "请求协议"),
                ExcelAlias.makeAlias("headers", "请求头信息"),
                ExcelAlias.makeAlias("requestURI", "资源路径"),
                ExcelAlias.makeAlias("remoteHost", "主机地址"),
                ExcelAlias.makeAlias("queryString", "请求参数"),
                ExcelAlias.makeAlias("requestURL", "请求概略信息"),
                ExcelAlias.makeAlias("remoteHost", "客户端主机名或IP"),
                ExcelAlias.makeAlias("protocol", "请求协议类型以及版本"),
                ExcelAlias.makeAlias("requestBody", "请求body"),
                ExcelAlias.makeAlias("responseBody", "响应body"),
                ExcelAlias.makeAlias("createTime", "请求时间"),
                ExcelAlias.makeAlias("answer", "响应时间(毫秒)")
        ));
    }
}
